Binary Search Trees (BST): The Ordering Invariant
The Binary Search Tree structure is fundamental because it imposes a strict ordering invariant on all nodes, enabling efficient search and insertion.
Searching and Insertion Mechanics
Both searching for a key and inserting a new node follow the same pathfinding logic starting from the root:
- Comparison: Compare to the Current Node's value.
- Path Selection: If , move Left (L); if , move Right (R).
- Termination (Search): Stop when the node is found or when a NULL pointer is reached (key not present).
- Termination (Insertion): The new node is attached at the final NULL position found.
This directed traversal ensures that, in a balanced tree, the maximum number of comparisons needed is .
Successor & Predecessor: Key to Deletion
Finding the in-order Successor (the node with the next largest key) is essential for the deletion algorithm when the node to be removed has two children.
- If node has a Right Child: The successor is the minimum value in the right subtree. Move one step Right, then continuously follow Left pointers.
- If node has NO Right Child: The successor is the nearest ancestor for which is in 's left subtree.
Performance Characteristics: vs.
BSTs provide logarithmic performance only if the tree remains relatively balanced. If data is inserted in sorted order, the tree degenerates into a skewed list, resulting in worst-case linear time complexity.
| Operation | Average Case (Balanced) | Worst Case (Skewed) |
|---|---|---|
| Search | ||
| Insertion | ||
| Deletion | ||
| Finding Successor |
1. What is the sequence of moves (R/L) to search for 80?
Assume a BST is built with keys: 50, 25, 75, 60, 90, 80. The root is 50.
2. What scenario leads to the worst-case search time in a BST?
3. In the same BST (root 50), what is the in-order successor of the node with value 75?
The tree contains: 50, 25, 75, 60, 90, 80.
4. According to the BST ordering invariant, if a node has value 42, which value could NOT be in its left subtree?